package com.example.sourcecodelearning.modules.async;

import com.example.framework.common.exception.enums.GlobalErrorCodeConstants;
import com.example.framework.common.pojo.R;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.Collection;

/**
 * @author yuzhenxin
 * @date 2023-08-06 13:36
 */
@Slf4j
@Service
public class AsyncService {

    // 存放监听某个Id的长轮询集合
    // 线程同步结构
    private static final Multimap<String, DeferredResult<R<String>>> watchRequests = Multimaps.synchronizedMultimap(HashMultimap.create());

    @Value("${polling.timeoutValue:5000}")
    private long timeoutValue;

    public DeferredResult<R<String>> watch(String id) {
        // 延迟对象设置超时时间
        DeferredResult<R<String>> deferredResult = new DeferredResult<>(timeoutValue);
        deferredResult.onCompletion(() -> {
            log.info("调用完成");
            // 异步请求完成时移除 key，防止内存溢出
            watchRequests.remove(id, deferredResult);
        });
        deferredResult.onTimeout(() -> {
            log.error("调用超时");
            deferredResult.setResult(R.fail(GlobalErrorCodeConstants.RESPONSE_TIMEOUT));
        });
        // 注册长轮询请求
        watchRequests.put(id, deferredResult);
        log.debug("servlet 线程释放");
        return deferredResult;
    }

    public void publish(String id, String message) {
        // 数据变更 取出监听ID的所有长轮询请求，并一一响应处理
        if (watchRequests.containsKey(id)) {
            Collection<DeferredResult<R<String>>> deferredResults = watchRequests.get(id);
            for (DeferredResult<R<String>> deferredResult : deferredResults) {
                deferredResult.setResult(R.success(message));
            }
        }
    }
}
